package com.zds.passwordbox.fragment;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;

import com.zds.passwordbox.R;
import com.zds.passwordbox.common.util.TOTPUtil;
import com.zds.passwordbox.data.dao.AccountDao;
import com.zds.passwordbox.data.dao.domain.UserAccount;

import java.util.concurrent.TimeUnit;

public class CodeDialog extends DialogFragment {

    private TextView totpCode;
    private TextView textViewCountdown;
    private CountDownTimer countDownTimer;

    private final AccountDao accountDao;

    private final Long id;

    private String secretKey;

    public CodeDialog(AccountDao accountDao, Long id) {
        this.accountDao = accountDao;
        this.id = id;
    }

    @NonNull
    @Override
    @SuppressLint("SetTextI18n")
    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
        // Use the Builder class for convenient dialog construction.
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

        // Get the layout inflater.
        LayoutInflater inflater = requireActivity().getLayoutInflater();
        View view = inflater.inflate(R.layout.code_dialog, null);
        builder.setView(view);
        TextView title = new TextView(requireContext());
        title.setText("TOTP验证码");
        title.setGravity(Gravity.CENTER); //只是要求标题居中的话，这一句就够了；
        //但是剧中后字体字号位置等信息会变掉，因而需要其他的设定来保证与原生字体一致。
        title.setTextSize(25);
        title.setTextColor(Color.BLACK);
        builder.setCustomTitle(title);
        TextView username = view.findViewById(R.id.code_detail_account);
        totpCode = view.findViewById(R.id.code_detail_code);
        textViewCountdown = view.findViewById(R.id.textViewCountdown);
        Button button = view.findViewById(R.id.code_detail_confirm);
        button.setOnClickListener(v -> dismiss());
        // 获取账户数据
        UserAccount account = accountDao.queryOne(this.id);
        if (account == null) {
            totpCode.setText("查询出错！");
            return builder.create();
        }
        username.setText(account.getUsername());

        this.secretKey = account.getSecret();

        updateTOTPCode(this.secretKey);

        startCountdownTimer();


        // Create the AlertDialog object
        return builder.create();
    }

    private void updateTOTPCode(String secretKey) {
        // TOTP生成
        String totpPassword = null;
        try {
            totpPassword = TOTPUtil.generateCode(secretKey);
        } catch (Exception e) {
            new TipDialog("生成TOTP验证码失败，可尝试删除账户重建")
                    .show(requireActivity().getSupportFragmentManager(), "codeGenerate");
        }
        this.totpCode.setText(totpPassword);
    }

    private void startCountdownTimer() {
        // 总倒计时时长,TOTP默认的时间步长为30秒
        long timeStepSeconds = 30;

        long currentTimeSeconds = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis());
        long timeStep = currentTimeSeconds / timeStepSeconds;

        long nextTimeStep = timeStep + 1;
        long nextTimeStepBegin = nextTimeStep * timeStepSeconds;
        long timeRemaining = nextTimeStepBegin - currentTimeSeconds;
        countDownTimer = new CountDownTimer(timeRemaining * 1000, 1000) {
            @Override
            @SuppressLint("SetTextI18n")
            public void onTick(long millisUntilFinished) {
                long secondsRemaining = TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished);
                textViewCountdown.setText(secondsRemaining + "s");
            }

            @Override
            public void onFinish() {
                // 倒计时结束时，重新生成验证码
                updateTOTPCode(secretKey);
                startCountdownTimer();
            }
        };
        countDownTimer.start();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
    }
}
